package com.net.request

import com.net.NetUtils
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File

class PostFileRequestBuilder : BaseRequestBuilder() {
    private var file:File? = null
    override fun build(): NetUtils {
        val build = Request.Builder()
        //URL 参数
        build.url(url)
        //请求tag
        tag?.let {
            build.tag(tag)
        }
        //请求header
        headers?.let {
            build.headers(generateHeader(it))
        }
        //请求方式
        build.post(getBody(params,file))
        return NetUtils(build.build())
    }

    private fun getBody(params: MutableMap<String, String>?, file: File?): RequestBody {
        val builder = MultipartBody.Builder()
        params?.forEach { (key, value) ->
            builder.addFormDataPart(key, value)
        }
        file?.let {
            builder.addFormDataPart("",file.name, it.asRequestBody("application/octet-stream".toMediaType()))
        }
        return builder.build()
    }

    fun file(file: File):PostFileRequestBuilder{
        this.file = file
        return this
    }
}
